﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls.UI;
using System.IO;
using Telerik.WinControls.Data;
using System.Data.SqlClient;
using log4net;
namespace QuanLyNhaSach
{
    public partial class frmPhanQuyen : Form
    {
        public frmPhanQuyen()
        {
            InitializeComponent();
        }

        static frmPhanQuyen doituong = null;
        public static frmPhanQuyen TaoDoiTuong()
        {
            if (doituong == null)
                doituong = new frmPhanQuyen();
            return doituong;
        }

        #region "Khai bao bien"
        sv_QuanLyNhaSach.AdapterClient service = new sv_QuanLyNhaSach.AdapterClient();
        private ILog logger;
        DataTable bang_tam;

        #endregion
        private void frmPhanQuyen_Load(object sender, EventArgs e)
        {            
            try
            {
                //Tao Cột cho Bảng Tạm
                bang_tam = new DataTable();
                bang_tam.Columns.Add("MaNhom", typeof(string));
                bang_tam.Columns.Add("MaForm", typeof(string));
                bang_tam.Columns.Add("Them", typeof(bool));
                bang_tam.Columns.Add("Xoa", typeof(bool));
                bang_tam.Columns.Add("Sua", typeof(bool));
                bang_tam.Columns.Add("Toanquyen", typeof(bool));

                logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                LoadNhomQuyen();
                loadchitietphanquyen();               
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        #region "loadnhom quyen va chi tiet phan quyen"
        private void LoadNhomQuyen()
        {
            //Chinh do dai cua cac cot trong muiltcombobox
            RadMultiColumnComboBoxElement multiColumnComboElement = this.cmb_nhomquyen.MultiColumnComboBoxElement;
            multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
            multiColumnComboElement.DropDownMinSize = new Size(200, 100);
            //load nhom quyen len combobox
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(service.selectqueryByText("select manhom,tennhom from NhomQuyen")));
            if (ds.Tables.Count > 0)
            {
                ds.Tables[0].Columns.Add("STT", typeof(int));
                DataRow dr;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    dr = ds.Tables[0].NewRow();
                    dr["STT"] = i + 1;
                    ds.Tables[0].Rows[i]["STT"] = dr["STT"].ToString();
                    //Xoa bỏ quyền Admin
                    if ("1" == ds.Tables[0].Rows[i]["MaNhom"].ToString().Trim())
                        ds.Tables[0].Rows[i].Delete();
                }

                cmb_nhomquyen.DataSource = ds.Tables[0];
                cmb_nhomquyen.DisplayMember = "tennhom";
                cmb_nhomquyen.ValueMember = "manhom";                
            }
            FilterDescriptor des_mh = new FilterDescriptor(this.cmb_nhomquyen.DisplayMember, FilterOperator.StartsWith, string.Empty);
            cmb_nhomquyen.EditorControl.FilterDescriptors.Add(des_mh);
        }        
        private void loadchitietphanquyen()
        {
            //hiện tên form trên coblumm maform
            DataSet ds1 = new DataSet();
            ds1.ReadXml(new StringReader(service.selectqueryByText("select * from Form")));
            if (ds1.Tables.Count > 0)
            {
                Telerik.WinControls.UI.GridViewComboBoxColumn txtgrid = (Telerik.WinControls.UI.GridViewComboBoxColumn)gv_phanquyen.Columns[2];
                txtgrid.DataSource = ds1.Tables[0];
                txtgrid.DisplayMember = "tenform";
                txtgrid.ValueMember = "maform";                
            }
            ////load danh sach chi tiet phan quyen theo ten nhom
            //DataSet ds = new DataSet();
            //ds.ReadXml(new StringReader(service.selectqueryByText("select * from chitietphanquyen where maform='" + cmb_nhomquyen.SelectedValue.ToString() + "'")));
            //if (ds.Tables.Count > 0)
            //{

            //    ds.Tables[0].Columns.Add("stt", typeof(int));
            //    gv_phanquyen.DataSource = ds.Tables[0];
            //    DataRow dr;
            //    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            //    {
            //        dr = ds.Tables[0].NewRow();
            //        dr["stt"] = i + 1;
            //        ds.Tables[0].Rows[i]["stt"] = dr["stt"].ToString();                 
            //    }
            //}
        }
        #endregion

        private void cmb_nhomquyen_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmb_nhomquyen.Text.Trim() == "")
                    txt_manhomquyen.Text = "";
                else
                {
                    txt_manhomquyen.Text = cmb_nhomquyen.SelectedValue.ToString();

                    DataSet ds2 = new DataSet();
                    ds2.ReadXml(new StringReader(service.selectqueryByText("select * from ChiTietPhanQuyen where manhom='" + cmb_nhomquyen.SelectedValue.ToString() + "'")));
                    if (ds2.Tables.Count > 0)
                    {

                        ds2.Tables[0].Columns.Add("STT", typeof(int));
                        gv_phanquyen.DataSource = ds2.Tables[0];
                        DataRow dr;
                        for (int i = 0; i < ds2.Tables[0].Rows.Count; i++)
                        {
                            dr = ds2.Tables[0].NewRow();
                            dr["STT"] = i + 1;
                            ds2.Tables[0].Rows[i]["STT"] = dr["STT"].ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        private void bt_luu_Click(object sender, EventArgs e)
        {
            try
            {
                if (bang_tam.Rows.Count > 0)
                {
                    for (int i = 0; i < bang_tam.Rows.Count; i++)
                    {
                        if (!service.UpdateCTPQ(bang_tam.Rows[i]["MaNhom"].ToString().Trim(), bang_tam.Rows[i]["MaForm"].ToString().Trim(), bool.Parse(bang_tam.Rows[i]["Them"].ToString()), bool.Parse(bang_tam.Rows[i]["Xoa"].ToString()), bool.Parse(bang_tam.Rows[i]["Sua"].ToString()), bool.Parse(bang_tam.Rows[i]["ToanQuyen"].ToString())))
                        {
                            MessageBox.Show("Cập nhật thất bại", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    
                }
                string manhom = gv_phanquyen.CurrentRow.Cells[1].Value.ToString().Trim();
                string maform = gv_phanquyen.CurrentRow.Cells[2].Value.ToString().Trim();
                bool them = kiem_traPhanQuyen(gv_phanquyen.CurrentRow.Cells[3].Value.ToString().Trim());
                bool xoa = kiem_traPhanQuyen(gv_phanquyen.CurrentRow.Cells[4].Value.ToString());
                bool sua = kiem_traPhanQuyen(gv_phanquyen.CurrentRow.Cells[5].Value.ToString());
                bool toanquyen = kiem_traPhanQuyen(gv_phanquyen.CurrentRow.Cells[6].Value.ToString());            
                if (!service.UpdateCTPQ(manhom, maform, them, xoa, sua, toanquyen))
                {
                    MessageBox.Show("Cập nhật thất bại", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                MessageBox.Show("Cập nhật thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                loadchitietphanquyen();
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }                            
            errorProvider1.Clear();
        }
        private bool kiem_traPhanQuyen(string chuoi_kiem_tra)
        {
            return chuoi_kiem_tra != "Off" ? true : false;
        }                

        private void gv_phanquyen_CurrentRowChanged(object sender, CurrentRowChangedEventArgs e)
        {
             try
            {
                if (cmb_nhomquyen.Text.Trim() == "")
                {
                    
                }
                else
                {
                    DataRow dr;
                    if (gv_phanquyen.Rows.Count > 0)
                    {
                        if (bang_tam.Rows.Count > 0)
                        for (int i = 0; i < bang_tam.Rows.Count; i++)
                        {
                            if (bang_tam.Rows[i]["MaForm"].ToString().Trim() == e.OldRow.Cells["MaForm"].Value.ToString().Trim())
                                bang_tam.Rows[i].Delete();
                            //return;
                        }                        
                        dr = bang_tam.NewRow();
                        dr["MaNhom"] = e.OldRow.Cells["MaNhom"].Value;
                        dr["MaForm"] = e.OldRow.Cells["MaForm"].Value;
                        dr["Them"] = kiem_traPhanQuyen(e.OldRow.Cells["Them"].Value.ToString());
                        dr["Xoa"] =kiem_traPhanQuyen(e.OldRow.Cells["Xoa"].Value.ToString());
                        dr["Sua"] =kiem_traPhanQuyen(e.OldRow.Cells["Sua"].Value.ToString());
                        dr["ToanQuyen"] = kiem_traPhanQuyen(e.OldRow.Cells["Toanquyen"].Value.ToString());
                        bang_tam.Rows.Add(dr);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: "+ex.Message);
            }
        }

        private void frmPhanQuyen_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bang_tam.Rows.Count > 0)
            {
                if (MessageBox.Show("Bạn đã thay đổi chức năng nhóm quyền. Bạn muốn cập nhật không?", "Cảnh Báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                {
                    for (int i = 0; i < bang_tam.Rows.Count; i++)
                    {
                        if (!service.UpdateCTPQ(bang_tam.Rows[i]["MaNhom"].ToString().Trim(), bang_tam.Rows[i]["MaForm"].ToString().Trim(), bool.Parse(bang_tam.Rows[i]["Them"].ToString()), bool.Parse(bang_tam.Rows[i]["Xoa"].ToString()), bool.Parse(bang_tam.Rows[i]["Sua"].ToString()), bool.Parse(bang_tam.Rows[i]["ToanQuyen"].ToString())))
                        {
                            MessageBox.Show("Cập nhật thất bại", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }
                }
            }
        }
        
    }
}
